package com.yige.service.mongoService

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBCursor
import com.mongodb.DBObject
import com.yige.service.BasicMongoService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.stereotype.Service

/**
 * Created by sunhao on 2015/9/17 0017.
 */


abstract class BasicMongoServiceImp implements BasicMongoService {

    @Autowired
    MongoTemplate mongoTemplate

    abstract DBCollection getCollection()


    @Override
    List<DBObject> findList() {
        List<DBObject> list = new ArrayList<>()
        DBObject dbObject
        DBCursor cursor = getCollection().find()
        while (cursor.hasNext()){
            dbObject = cursor.next()
            list.add(dbObject)
        }
        return list
    }

    @Override
    List<DBObject> findListByQuery(BasicDBObject query) {
        List<DBObject> list = new ArrayList<>()
        DBObject dbObject
        DBCursor cursor
        if(query == null){
            list = findList()
        }else{
            cursor = getCollection().find(query)
            while (cursor.hasNext()){
                dbObject = cursor.next()
                list.add(dbObject)
            }
        }
        return list
    }

    @Override
    DBObject findOneById(Object _id) {
        return getCollection().findOne([_id:_id]as BasicDBObject)
    }

    @Override
    DBObject findOneByQuery(BasicDBObject query) {
        return  getCollection().findOne(query)
    }

    @Override
    boolean insertOne(DBObject dbObject) {
        getCollection().insert(dbObject)
        return true
    }

    @Override
    boolean updateOne(Object _id, DBObject dbObject) {
        getCollection().update(
                [_id:_id]as BasicDBObject,[$set:dbObject]as BasicDBObject
        )
        return true
    }

    @Override
    boolean deleteOne(Object _id) {
        getCollection().remove([_id:_id]as BasicDBObject)
        return true
    }


    @Override
    List<DBObject> findListDescendingByDate() {
        List<DBObject> list = new ArrayList<>()
        DBObject dbObject
        DBCursor cursor = getCollection().find([status:[$ne:-1]as BasicDBObject]as BasicDBObject).sort([date:-1]as BasicDBObject)
        while (cursor.hasNext()){
            dbObject = cursor.next()
            list.add(dbObject)
        }
        return list
    }

    @Override
    List<DBObject> findListAscendingByDate() {
        List<DBObject> list = new ArrayList<>()
        DBObject dbObject
        DBCursor cursor = getCollection().find().sort([date:1]as BasicDBObject)
        while (cursor.hasNext()){
            dbObject = cursor.next()
            list.add(dbObject)
        }
        return list
    }

    @Override
    boolean removeCollection(){
        getCollection().drop()
        return true
    }
}
